package com.kuaiditu.assistant.module.retrofit;

import android.content.Context;

import com.kuaiditu.assistant.util.ToastUtil;

import io.reactivex.Observer;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;


public abstract class ProgressSubscriber<T> implements ProgressCancelListener, Observer<T> {

    private static final String TAG = "ProgressSubscriber";
    private ProgressDialogHandler mProgressDialogHandler;
    private Context context;
    private Disposable mDisposable;


    public ProgressSubscriber(Context context,String hintText) {
        this.context = context;
        mProgressDialogHandler = new ProgressDialogHandler(context, this, true, hintText);

    }
    public ProgressSubscriber(Context context) {
        this.context = context;
        mProgressDialogHandler = new ProgressDialogHandler(context, this, true);

    }
    private void showProgressDialog(){
        if (mProgressDialogHandler != null) {
            mProgressDialogHandler.obtainMessage(ProgressDialogHandler.SHOW_PROGRESS_DIALOG).sendToTarget();
        }
    }

    private void dismissProgressDialog(){
        if (mProgressDialogHandler != null) {
            mProgressDialogHandler.obtainMessage(ProgressDialogHandler.DISMISS_PROGRESS_DIALOG).sendToTarget();
            mProgressDialogHandler = null;
        }
    }

    @Override
    public void onSubscribe(@NonNull Disposable d) {
        mDisposable = d;
        onStart();
    }

    @Override
    public void onComplete() {
        dismissProgressDialog();
        onFinish();
    }


    @Override
    public void onError(Throwable e) {
        e.printStackTrace();
        dismissProgressDialog();
        handleError(e);
        onFinish();
    }

    public void onStart() {
        showProgressDialog();
    }

    @Override
    public abstract void onNext(T t);


    public abstract void onFinish();

    @Override
    public void onCancelProgress() {
        if (!this.mDisposable.isDisposed()) {
            this.mDisposable.dispose();
        }
    }

    public void handleError(Throwable e) {

        ToastUtil.showToast(e.getMessage());

//        Toast.makeText(context, e.getMessage(), Toast.LENGTH_SHORT).show();
    }
}
